#coding=utf-8
import pandas as pd
import statsmodels.api as sm


df = pd.read_csv("F:/binary.csv")


# print df.head()
#    admit  gre   gpa  rank
# 0      0  380  3.61     3
# 1      1  660  3.67     3
# 2      1  800  4.00     1
# 3      1  640  3.19     4
# 4      0  520  2.93     4

df.columns = ["admit", "gre", "gpa", "prestige"]
# # print df.columns
# # #
# # #
# # #
# print df.std()
# admit      0.466087
# gre      115.516536
# gpa        0.380567
# prestige   0.944460
# # # #
# print pd.crosstab(df['admit'], df['prestige'], rownames=['admit'])
# prestige   1   2   3   4
# admit
# 0         28  97  93  55
# 1         33  54  28  12
# # #
# # # # plot all of the columns
# # # df.hist()
# # # plt.show()
# get_dummies来将”prestige”一列虚拟化。
# get_dummies为每个指定的列创建了新的带二分类预测变量的DataFrame
dummy_ranks = pd.get_dummies(df['prestige'], prefix='prestige')
# print dummy_ranks.head()
# # # #    prestige_1  prestige_2  prestige_3  prestige_4
# # # # 0           0           0           1           0
# # # # 1           0           0           1           0
# # # # 2           1           0           0           0
# # # # 3           0           0           0           1
# # # # 4           0           0           0           1
# # #
# # #
cols_to_keep = ['admit', 'gre', 'gpa']
# ix特殊字段索引
# obj.ix[val]	选取 DataFrame 的单个行或一组行
# obj.ix[:,val]	选取单个列或列子集
data = df[cols_to_keep].join(dummy_ranks.ix[:, 'prestige_2':])
# print data.head()
# # # #    admit  gre   gpa  prestige_2  prestige_3  prestige_4
# # # # 0      0  380  3.61           0           1           0
# # # # 1      1  660  3.67           0           1           0
# # # # 2      1  800  4.00           0           0           0
# # # # 3      1  640  3.19           0           0           1
# # # # 4      0  520  2.93           0           0           1
# # #
# # #
data['intercept'] = 1.0
# #
# #
train_cols = data.columns[1:]
print train_cols
# Index([gre, gpa, prestige_2, prestige_3, prestige_4], dtype=object)
#
logit = sm.Logit(data['admit'], data[train_cols])
# #
# #
result = logit.fit()
# #
# #
import copy
combos = copy.deepcopy(data)


predict_cols = combos.columns[1:]
# combos
# admit  gre   gpa  prestige_2  prestige_3  prestige_4   predict
# 0  380  3.61           0           1           0          1
# 1  660  3.67           0           1           0          0
# 1  800  4.00           0           0           0          1
# 1  640  3.19           0           0           1          0
# 0  520  2.93           0           0           1          1
combos['intercept'] = 1.0


combos['predict'] = result.predict(combos[predict_cols])


total = 0
hit = 0
for value in combos.values:
    predict = value[-1]
    admit = int(value[0])

    if predict > 0.5:
        total += 1
        if admit == 1:
            hit += 1

print 'Total: %d, Hit: %d, Precision: %.2f' % (total, hit, 100.0*hit/total)